import { defineStore } from 'pinia'
//选项式写法
// export const useUserStore = defineStore('user', {
//   state: () => ({
//     name: 'Guest',
//     isLogin: false,
//     token: localStorage.getItem('ACCESS_TOKEN') || '',
//   }),
//   actions: {
//     async login(name: string) {
//       state.name = name
//       state.isLogin = true
//       // 登录成功后存储token
//       localStorage.setItem('ACCESS_TOKEN', 'your_token')
//       state.token = 'your_token'
//     },
//     async logout() {
//       localStorage.removeItem('ACCESS_TOKEN')
//       state.token = ''
//       state.isLogin = false
//     },
//   },
// })

//组合式API写法
import { reactive, toRefs, type Ref } from 'vue'

interface UserInfo {
    avatar?: string;
    code?: string;
    phoneModelId: number;
    phoneNumber: string;
    username: string;
}

export const useUserStore = defineStore('user', () => {
  const state = reactive({
      name: 'Guest',
      isLogin: false,
      userInfo: {
        avatar: '',
        code: '',
        phoneModelId: 30,
        phoneNumber: '',
        username: ''
      } as UserInfo,
      token: localStorage.getItem('ACCESS_TOKEN') || ''
  })
  
  const login = async (name: string, token: string) => {
      state.name = name
      state.isLogin = true
      state.token = token
      localStorage.setItem('ACCESS_TOKEN', token)
  }
  
  const logout = () => {
      localStorage.removeItem('ACCESS_TOKEN')
      state.token = ''
      state.isLogin = false
  }
  const setUserInfo = (userInfo: Partial<UserInfo>) => {
    Object.assign(state.userInfo, userInfo);
  }
  return { 
      ...toRefs(state),
      login,
      logout,
      setUserInfo
  } as unknown as { // 添加类型断言
    name: Ref<string>
    isLogin: Ref<boolean>
    token: Ref<string>
    login: (name: string, token: string) => Promise<void>
    logout: () => void
  }
}, {
    // 新增持久化配置
    persist: {
        key: 'user-store',
        paths: ['name', 'isLogin', 'token','userInfo'],
        storage: localStorage
    }
})